<template>
    <el-form ref="formRef" :model="form" labelWidth="120px" label-suffix="：">
        <el-steps :active="active">
            <template v-for="(step, index) in steps" :key="index">
                <el-step>
                    <template #title>
                        <span class="step-title" @click="active = step.value">{{ step.title }}</span>
                    </template>
                </el-step>
            </template>
        </el-steps>

        <div v-show="active === 1" class="step1">
            <el-form-item label="节点名称">
                <el-input v-model="form.nodeName"></el-input>
            </el-form-item>
            <el-form-item label="节点ID">
                <el-input v-model="form.typeConcatName" disabled></el-input>
            </el-form-item>
            <el-form-item label="数据库源" prop="datasourceId">

                <el-select v-model="form.datasourceId" @change="rDsChange" filterable style="width: 100%"
                           :loading="loading">
                    <el-option
                            v-for="item in rDsList" :key="item.datasourceId"
                            :label="item.datasourceGroup + '_' + item.datasourceName + '_' + item.datasourceType + '(' + item.datasourceCode + ')'"
                            :value="item.datasourceId"/>
                </el-select>
            </el-form-item>
            <el-form-item
                    v-if="form.datasourceType==='postgresql' || form.datasourceType==='oracle' ||form.datasourceType==='sqlserver'"
                    label="Schema">
                <el-select v-model="form.schema" filterable style="width: 100%" @change="schemaChange">
                    <el-option
                            v-for="item in schemaList"
                            :key="item"
                            :label="item"
                            :value="item"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="数据库表名" prop="table">
                <el-select v-model="form.table" default-first-option filterable style="width: 100%" :loading="loading">
                    <el-option v-for="item in rTbList" :key="item" :label="item" :value="item"/>
                </el-select>
            </el-form-item>
    <!--        <el-form-item label="转义符号" prop="symbols">-->
    <!--            <el-input v-model="form.symbols"></el-input>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="connection" prop="fields">-->
    <!--            <el-input v-model="form.connection" type="textarea" placeholder="请输入内容"/>-->
    <!--        </el-form-item>-->
            <el-form-item label="流输出" prop="isStream">
                <el-switch v-model="form.isStream" active-value="Y" inactive-value="N"></el-switch>
            </el-form-item>
<!--            <el-form-item label="批量提交" prop="use_batch">-->
<!--                <el-switch v-model="form.use_batch" active-value="Y" inactive-value="N"></el-switch>-->
<!--            </el-form-item>-->
            <el-form-item label="提交数量" prop="fields">
                <el-input-number v-model="form.commit"></el-input-number>
            </el-form-item>
            <dialog-footer @ok="submitForm" @cancel="cancel" ok-text="保存">
                <el-button type="success" @click="active = 2">下一步</el-button>
            </dialog-footer>
<!--        <el-form-item label="specify_fields" prop="specify_fields">-->
<!--            <el-switch v-model="form.specify_fields" active-value="Y" inactive-value="N"></el-switch>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="字段">-->
<!--            <el-table :data="form.fields.field" style="width: 100%">-->
<!--                <el-table-column prop="column_name" label="字段名" width="120">-->
<!--&lt;!&ndash;                    <el-input v-model="form.fields.field[index].column_name" placeholder="请输入字段名"&ndash;&gt;-->
<!--&lt;!&ndash;                               style="width: 100%"/>&ndash;&gt;-->
<!--                    <template #default="scope">-->
<!--                        <el-input v-model="scope.row.column_name"></el-input>-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column prop="stream_name" label="流名" width="120">-->
<!--                    <template #default="scope">-->
<!--                        <el-input v-model="scope.row.stream_name"></el-input>-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--            </el-table>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="备注">-->
<!--            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="忽略错误">-->
<!--            <el-radio-group v-model="form.ignore_errors">-->
<!--                <el-radio label="Y">是</el-radio>-->
<!--                <el-radio label="N">否</el-radio>-->
<!--            </el-radio-group>-->
<!--        </el-form-item>-->
        </div>
        <div v-show="active === 2" class="step2">
            <el-form-item label="字段">
                <div style="margin-bottom: 10px;">
                    <el-button
                        type="primary"
                        size="small"
                        @click="getTableColumns"
                    >从库表读入</el-button>
                    <el-button
                        type="primary"
                        size="small"
                        @click="addField"
                    >新增字段</el-button>
                    <el-button
                        type="danger"
                        size="small"
                        @click="batchDelete"
                        :disabled="selectedRows.length === 0"
                    >删除选中</el-button>

                </div>
                <el-table :data="form.fields.field" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="30"/>
                    <el-table-column prop="column_name" label="字段名称" width="150">
                        <template #default="scope">
                            <el-input v-model="scope.row.column_name" placeholder="请输入字段名称"></el-input>
                        </template>
                    </el-table-column>
<!--                    <el-table-column porp="stream_name" label="流名称" width="150">-->
<!--                        <template #default="scope">-->
<!--                            <el-input v-model="scope.row.stream_name" placeholder="请选择流名称"/>-->
<!--                        </template>-->
<!--                    </el-table-column>-->
                    <el-table-column prop="type" label="字段类型" width="180">
                        <template #default="scope">
                            <el-select v-model="scope.row.type" placeholder="请选择字段类型">
                                <el-option v-model="scope.row.type"
                                           v-for="item in typeList"
                                           :key="item.dictLabel"
                                           :label="item.dictLabel"
                                           :value="item.dictLabel"/>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #default="scope">
                            <el-button
                                type="danger"
                                size="small"
                                @click="deleteField(scope.$index)"
                                :disabled="form.fields.field.length === 0"
                            >删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <dialog-footer @ok="submitForm" @cancel="cancel" ok-text="保存">
                <el-button type="success" @click="active = 1">上一步</el-button>
            </dialog-footer>

      </div>
    </el-form>

</template>

<script setup>
import {defineComponent, ref, onMounted, reactive, watch} from 'vue';
import {flowServiceStore} from '@data/store/flow';

const flowCount = flowServiceStore();
import {storeToRefs} from 'pinia';

const {flowData} = storeToRefs(flowCount);
import {search as datasourceList} from '@data/api/data/datasource'
import { selectTables, selectSchema, selectColumns, selectTableInfo, getTableStructureByQuerySql } from '@data/api/data/datacollection'
import { getDicts } from '@base/api/base/dict/data'

import {cloneDeep} from "lodash-es";
import {ElMessage} from "element-plus";

defineComponent({
    name: 'TableOutput',
});
const props = defineProps({
    detailObject: {
        type: Object,
        default: () => {
        },
    },
})

const steps = ref([
    { value: 1, title: '基础属性' },
    { value: 2, title: '输出参数' }
]);
const active = ref(1);

const rDsList = ref([]);
const rTbList = ref([]);
const schemaList = ref([]);
const loading = ref(false);

const typeList = ref([]);
const getTypeList= () => {
    getDicts('ktr_field_type').then((response) => {
      typeList.value = response.data
      console.log(typeList.value)
    })
};

const form = reactive({
    nodeName: '',
    name: '',
    type: 'TableOutput',
    copies: 1,
    distribute: 'Y',

    // remark: '',
    datasourceId: '',
    datasourceType: '',
    connection: '',
    schema: '',
    table: '',
    // symbols: '',
    // ignore_errors: "Y",
    commit: 1,
    isStream: '',
    use_batch: 'Y',
    specify_fields: 'N',
    fields: {
        field: []
    },

    GUI: {
        xloc: 1,
        yloc: 1,
        draw: 'Y'
    }

});


const emit = defineEmits(['cancel']);

onMounted(() => {
    getJdbcDs();
    getTypeList();
    form.nodeName = flowData.value[props.detailObject.id]?.nodeName || props.detailObject.data.label;
    form.datasourceId = flowData.value[props.detailObject.id]?.datasourceId || '';
    form.datasourceType = flowData.value[props.detailObject.id]?.datasourceType || '';
    form.connection = flowData.value[props.detailObject.id]?.connection || '';
    form.schema = flowData.value[props.detailObject.id]?.schema || '';
    form.table = flowData.value[props.detailObject.id]?.table || '';
    // form.remark = flowData.value[props.detailObject.id]?.remark || '';
    // form.symbols = flowData.value[props.detailObject.id]?.symbols || '';
    // form.ignore_errors = flowData.value[props.detailObject.id]?.ignore_errors || 'Y';
    form.commit = flowData.value[props.detailObject.id]?.commit || 1;
    form.isStream = flowData.value[props.detailObject.id]?.isStream || '';
    // form.use_batch = flowData.value[props.detailObject.id]?.use_batch || 'Y';
    form.specify_fields = flowData.value[props.detailObject.id]?.specify_fields || 'N';
    form.fields = cloneDeep(flowData.value[props.detailObject.id]?.fields) ||
        {
            field: []
        };
    form.name = props.detailObject.id;
    form.typeConcatName = `${props.detailObject.id}(${form.type}-${props.detailObject.id})`;

    form.distribute = flowData.value[props.detailObject.id]?.distribute || 'Y';

})

watch(() => form.datasourceId, (newVal, oldVal) => {
    if (form.datasourceType === 'postgresql' || form.datasourceType === 'oracle') {
        console.log("getSchema")
        getSchema();
    } else {
        getTables();
    }
});

const rDsChange = (e) => {
    // 清空
    form.table = '';
    rDsList.value.find((item) => {
        if (item.datasourceId === e) {
            form.datasourceGroup = item.datasourceGroup;
            form.datasourceName = item.datasourceName;
            form.datasourceType = item.datasourceType;
            form.connection = item.datasourceCode;
        }
    })
    form.fields.field = []
}

const getJdbcDs = () => {
    loading.value = true
    datasourceList({}).then(response => {
        const {list} = response.data
        rDsList.value = list //list.filter( item => item.jdbcUrl.includes('oracle'))
        loading.value = false
    })
}

const getSchema = () => {
    const obj = {
        datasourceId: form.datasourceId
    }
    selectSchema(obj).then(response => {
        console.log("response",response)
        schemaList.value = response.data
    })
}

const schemaChange = (e) => {
    console.log("e",e)
    form.schema = e
    // 获取可用表
    getTables()
}

// 获取表名
const getTables = () => {
    if (form.datasourceId) {
        let obj = {
            datasourceId: form.datasourceId
        }
        if (form.datasourceType == 'postgresql' || form.datasourceType == 'oracle') {
            obj.tableSchema = form.schema;
        }
        // 组装
        loading.value = true
        selectTables(obj).then(response => {
            if (response) {
                loading.value = false
                // rTbList.value = response.data
                rTbList.value = form.datasourceType === 'postgresql'
                    ? response.data.map(item => {
                        // 处理带schema前缀的表名（如：public.users -> users）
                        const dotIndex = item.indexOf('.')
                        return dotIndex > -1 ? item.slice(dotIndex + 1) : item
                    })
                    : response.data
            }
        })
    }

}

const getTableColumns = async () => {
    let tableName = form.table;
    if (form.datasourceType === 'postgresql' && form.schema) {
        tableName = `${form.schema}.${form.table}`;
    }
    const obj = {
      datasourceId: form.datasourceId,
      querySql:  ' select * from ' +  tableName
    }
    console.log("tableName",tableName)
    //获取表所有字段名
        getTableStructureByQuerySql(obj).then(response => {
            let arr = []
            console.log(response)
            response.data.forEach(item => {
                arr.push({
                    column_name:item[0].toLowerCase(),
                    stream_name: '',
                    type: item[1].toLowerCase(),
                    name: item,
                })
            })
            form.fields.field = cloneDeep(arr);
            ElMessage.success('解析成功')
      })

}

const selectedRows = ref([])
// 处理选择变化
const handleSelectionChange = (val) => {
    selectedRows.value = val
}
// 批量删除方法
const batchDelete = () => {
    if (selectedRows.value.length === 0) return
    const indexes = selectedRows.value.map(row =>
        form.fields.field.indexOf(row)
    ).sort((a,b) => b - a)
    indexes.forEach(index => {
        form.fields.field.splice(index, 1)
    })
    selectedRows.value = []
}

// 新增字段方法
const addField = () => {
    form.fields.field.push({
        column_name: '',
        stream_name: '',
        type: '',
        name: '',
    });
}

// 修改删除方法
const deleteField = (index) => {
    form.fields.field.splice(index, 1);
}

const submitForm = () => {
    form.fields.field.forEach((item) => {
        item.name = item.column_name;
    })
    flowCount.setFlowData(
        {
            ...flowData.value,
            [props.detailObject.id]: {
                ...form,
                name: `${form.type}-${form.name}`,
            }
        }
    )

    // 触发数据更新事件
    // emit('update-data', {
    //   id: props.detailObject.id,
    //   data: form
    // });
    console.log(flowData.value);
    emit('cancel');

}
const cancel = () => {
    emit('cancel');
}
</script>

<style scoped>

</style>